﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;

using System.IO;
using System.Drawing;

using ISS.CaseStudy.BLL;
using ISS.CaseStudy.Entities;

namespace CaseStudy.AdminPortal
{
    public partial class CaseStudyInfoDetail : System.Web.UI.Page
    {
        private bool isEdit = true;
        private bool isNew = false;
        private string id = string.Empty;
        private string mode = string.Empty;

        private string size = System.Configuration.ConfigurationManager.AppSettings["ImageMaxSize"].ToString();
        private string imagePath = System.Configuration.ConfigurationManager.AppSettings["ImagePath"].ToString();

        protected void Page_Load(object sender, EventArgs e)
        {
            loginInfo.Login();

            if (Request.QueryString["mode"] != null)
                mode = Request.QueryString["mode"].ToLower();

            if (Request.QueryString["id"] != null)
            {
                id = Request.QueryString["id"];
                isNew = false;
            }
            else
            {
                isNew = true;
            }

            if (!IsPostBack)
            {
                BindDropDownLists();
                BindTechnologyInfo(isNew);
                BindRelatedInfo(isNew);
            }

            if (!isNew)
            {
                if (!IsPostBack)
                {
                    BindData();

                    if (Request.QueryString["from"] != null)
                    {
                        divReminding.InnerHtml = "创建成功案例成功！";
                        divReminding.Visible = true;
                        divReminding.Style.Add("color", "Green");
                    }
                }

                if (mode.Equals("edit"))
                {
                    isEdit = true;
                    currentMapItem.InnerText = "编辑成功案例";
                }
                else
                {
                    isEdit = false;
                    currentMapItem.InnerText = "查看成功案例";

                    txtTitle.Enabled = false;
                    txtDescription.Enabled = false;
                    txtFileName.Enabled = false;
                    loadImage.Enabled = false;
                    txtCapability.Enabled = false;
                    txtQuote.Enabled = false;
                    txtLocation.Enabled = false;
                    txtOrganizationSize.Enabled = false;
                    txtOrganizationProfile.Enabled = false;
                    txtCountry.Enabled = false;
                    ddIndustry.Enabled = false;
                    ddClient.Enabled = false;
                    ddService.Enabled = false;

                    txtIndustry.Enabled = false;
                    txtClient.Enabled = false;
                    txtService.Enabled = false;

                    imgBtnConfirm.Visible = false;
                    imgBtnReset.Visible = false;

                    foreach (TableRow row in tblTechnology.Rows)
                    {
                        foreach (TableCell cell in row.Cells)
                        {
                            ItemShowing item = (ItemShowing)cell.Controls[0];
                            item.IsEnable = false;
                        }
                    }

                    foreach (TableRow row in tblRelated.Rows)
                    {
                        foreach (TableCell cell in row.Cells)
                        {
                            ItemShowing item = (ItemShowing)cell.Controls[0];
                            item.IsEnable = false;
                        }
                    }
                }
            }
            else
            {
                isEdit = false;
                currentMapItem.InnerText = "新建成功案例";
            }
        }

        protected void imgBtnReset_Click(object sender, EventArgs e)
        {
            divReminding.InnerHtml = "";
            divReminding.Visible = false;

            hiddenIndustry.Value = "0";
            hiddenClient.Value = "0";
            hiddenService.Value = "0";

            if (!isEdit)
            {   
                txtTitle.Text = string.Empty;
                txtDescription.Text = string.Empty;
                txtFileName.Text = string.Empty;
                txtCapability.Text = string.Empty;
                txtQuote.Text = string.Empty;
                txtLocation.Text = string.Empty;
                txtOrganizationSize.Text = string.Empty;
                txtOrganizationProfile.Text = string.Empty;
                txtCountry.Text = string.Empty;
                ddIndustry.SelectedIndex = 0;
                ddClient.SelectedIndex = 0;
                ddService.SelectedIndex = 0;
            }
            else
            {
                BindData();
            }
        }

        protected void imgBtnConfirm_Click(object sender, EventArgs e)
        {
            if (!ValidateDates())
            {
                hiddenIndustry.Value = "0";
                hiddenClient.Value = "0";
                hiddenService.Value = "0";

                return;
            }

            SaveImage();

            CaseStudyInfo caseStudyInfo = new CaseStudyInfo();
            caseStudyInfo.Title = HttpUtility.HtmlEncode(txtTitle.Text);
            caseStudyInfo.Description = HttpUtility.HtmlEncode(txtDescription.Text);
            caseStudyInfo.FileName = HttpUtility.HtmlEncode(txtFileName.Text);
            caseStudyInfo.Capability = HttpUtility.HtmlEncode(txtCapability.Text);
            caseStudyInfo.Quote = HttpUtility.HtmlEncode(txtQuote.Text);
            caseStudyInfo.Location = HttpUtility.HtmlEncode(txtLocation.Text);
            caseStudyInfo.OrganizationProfile = HttpUtility.HtmlEncode(txtOrganizationProfile.Text);
            caseStudyInfo.CountryAndRegion = HttpUtility.HtmlEncode(txtCountry.Text);
            caseStudyInfo.VisitCount = "0";

            caseStudyInfo.Technology = hiddenTechChosen.Value;
            caseStudyInfo.RelatedInformation = hiddenRelChosen.Value;

            int tempInt = -1;
            int.TryParse(HttpUtility.HtmlEncode(txtOrganizationSize.Text), out tempInt);
            if (tempInt > -1)
            {
                caseStudyInfo.OrganizationSize = tempInt.ToString();
            }

            string imgAddress = string.Empty;

            if (!string.IsNullOrEmpty(loadImage.FileName))
            {
                imgAddress = loadImage.FileName;
            }
            else
            {
                imgAddress = lblImageName.Text;
            }
            caseStudyInfo.ImageAddress = imgAddress;

            DataSet industryDataSet = IndustryBLL.GetAll();
            DataSet clientDataSet = ClientBLL.GetAll();
            DataSet serviceDataSet = ServiceBLL.GetAll();

            ListItem industryItem = new ListItem(txtIndustry.Text);

            caseStudyInfo.IndustryType = false;
            caseStudyInfo.IndustryValue = string.Empty;
            if (hiddenIndustry.Value.Equals("1") && (!ddIndustry.Items.Contains(industryItem)))
            {
                caseStudyInfo.IndustryType = true;
                caseStudyInfo.IndustryValue = HttpUtility.HtmlEncode(txtIndustry.Text);
            }
            else
            {
                caseStudyInfo.IndustryType = false;
                foreach (DataRow row in industryDataSet.Tables[0].Rows)
                {
                    if (HttpUtility.HtmlDecode(row["Value"].ToString()).Equals(ddIndustry.SelectedValue))
                    {
                        caseStudyInfo.IndustryValue = row["Id"].ToString();
                        break;
                    }
                }
            }

            ListItem clientItem = new ListItem(txtClient.Text);
            if (hiddenClient.Value.Equals("1") && (!ddClient.Items.Contains(clientItem)))
            {
                caseStudyInfo.ClientType = true;
                caseStudyInfo.ClientValue = HttpUtility.HtmlEncode(txtClient.Text);
            }
            else
            {
                caseStudyInfo.ClientType = false;
                foreach (DataRow row in clientDataSet.Tables[0].Rows)
                {
                    if (HttpUtility.HtmlDecode(row["Value"].ToString()).Equals(ddClient.SelectedValue))
                    {
                        caseStudyInfo.ClientValue = row["Id"].ToString();
                        break;
                    }
                }
            }

            ListItem serviceItem = new ListItem(txtService.Text);
            if (hiddenService.Value.Equals("1") && (!ddService.Items.Contains(serviceItem)))
            {
                caseStudyInfo.ServiceType = true;
                caseStudyInfo.ServiceValue = HttpUtility.HtmlEncode(txtClient.Text);
            }
            else
            {
                caseStudyInfo.ServiceType = false;
                foreach (DataRow row in serviceDataSet.Tables[0].Rows)
                {
                    if (HttpUtility.HtmlDecode(row["Value"].ToString()).Equals(ddService.SelectedValue))
                    {
                        caseStudyInfo.ServiceValue = row["Id"].ToString();
                        break;
                    }
                }
            }

            caseStudyInfo.ModifyTime = DateTime.Now;

            string errorDescription = string.Empty;
            int caseStudyId = -1;

            if (!isEdit)
            {
                if (!CaseStudyBLL.Insert(caseStudyInfo, out errorDescription, out caseStudyId))
                {
                    divReminding.InnerHtml = errorDescription;
                    divReminding.Visible = true;
                    divReminding.Style.Add("color", "Red");
                }
            }
            else
            {
                caseStudyInfo.Id = id;
                if (CaseStudyBLL.Update(caseStudyInfo, out errorDescription))
                {
                    divReminding.InnerHtml = "修改成功案例成功！";
                    divReminding.Visible = true;
                    divReminding.Style.Add("color", "Green");

                    BindDropDownLists();
                    BindData();
                }
                else
                {
                    divReminding.InnerHtml = errorDescription;
                    divReminding.Visible = true;
                    divReminding.Style.Add("color", "Red");
                }

            }

            BindTechnologyInfo(caseStudyInfo.Technology);
            BindRelatedInfo(caseStudyInfo.RelatedInformation);

            if (caseStudyId > 0)
            {
                string navgationUrl = string.Format("CaseStudyInfoDetail.aspx?id={0}&mode=edit&from=add", caseStudyId.ToString());
                Response.Redirect(navgationUrl);
            }
        }

        protected void imgBtnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("CaseStudyManager.aspx");
        }

        private void BindData()
        {
            CaseStudyInfo caseStudyInfo = CaseStudyBLL.GetInfo(id);
            txtTitle.Text = HttpUtility.HtmlDecode(caseStudyInfo.Title);

            if (!string.IsNullOrEmpty(caseStudyInfo.FileName))
            {
                txtFileName.Text = HttpUtility.HtmlDecode(caseStudyInfo.FileName);
            }

            if (!string.IsNullOrEmpty(caseStudyInfo.ImageAddress))
            {
                divImage.Visible = true;
                lblImageName.Text = caseStudyInfo.ImageAddress;
                imgShow.Visible = true;
                imgShow.ImageUrl = "images/" + caseStudyInfo.ImageAddress;
            }
            else
            {
                imgShow.Visible = false;
            }

            DataSet dataSetIndustry = IndustryBLL.GetAll();
            foreach (DataRow row in dataSetIndustry.Tables[0].Rows)
            {
                if (row["Id"].ToString().Equals(caseStudyInfo.IndustryValue))
                {
                    ddIndustry.SelectedValue = HttpUtility.HtmlDecode(row["Value"].ToString());
                    break;
                }
            }

            DataSet dataSetClient = ClientBLL.GetAll();
            foreach (DataRow row in dataSetClient.Tables[0].Rows)
            {
                if (row["Id"].ToString().Equals(caseStudyInfo.ClientValue))
                {
                    ddClient.SelectedValue = HttpUtility.HtmlDecode(row["Value"].ToString());
                    break;
                }
            }

            DataSet dataSetService = ServiceBLL.GetAll();
            foreach (DataRow row in dataSetService.Tables[0].Rows)
            {
                if (row["Id"].ToString().Equals(caseStudyInfo.ServiceValue))
                {
                    ddService.SelectedValue = HttpUtility.HtmlDecode(row["Value"].ToString());
                    break;
                }
            }

            txtDescription.Text = HttpUtility.HtmlDecode(caseStudyInfo.Description);
            txtCapability.Text = HttpUtility.HtmlDecode(caseStudyInfo.Capability);
            txtQuote.Text = HttpUtility.HtmlDecode(caseStudyInfo.Quote);
            txtLocation.Text = HttpUtility.HtmlDecode(caseStudyInfo.Location);
            txtOrganizationSize.Text = HttpUtility.HtmlDecode(caseStudyInfo.OrganizationSize);
            txtOrganizationProfile.Text = HttpUtility.HtmlDecode(caseStudyInfo.OrganizationProfile);
            txtCountry.Text = HttpUtility.HtmlDecode(caseStudyInfo.CountryAndRegion);

            hiddenIndustry.Value = "0";
            hiddenClient.Value = "0";
            hiddenService.Value = "0";
        }

        private void BindDropDownLists()
        {
            ddIndustry.Items.Clear();
            ddClient.Items.Clear();
            ddService.Items.Clear();

            ddIndustry.Items.Add("");
            ddClient.Items.Add("");
            ddService.Items.Add("");

            DataSet dataSetIndustry = IndustryBLL.GetAll();
            foreach (DataRow row in dataSetIndustry.Tables[0].Rows)
            {
                ddIndustry.Items.Add(HttpUtility.HtmlDecode(row["Value"].ToString()));
            }

            DataSet dataSetClient = ClientBLL.GetAll();
            foreach (DataRow row in dataSetClient.Tables[0].Rows)
            {
                ddClient.Items.Add(HttpUtility.HtmlDecode(row["Value"].ToString()));
            }

            DataSet dataSetService = ServiceBLL.GetAll();
            foreach (DataRow row in dataSetService.Tables[0].Rows)
            {
                ddService.Items.Add(HttpUtility.HtmlDecode(row["Value"].ToString()));
            }
        }

        private void BindRelatedInfo(bool isNew)
        {
            List<string> relatedIds;

            if (!isNew)
            {
                relatedIds = CaseStudyRelatedInformationBLL.GetInfoIdsByCaseStudyId(id);
            }
            else
            {
                relatedIds = new List<string>();
            }

            BindRelated(relatedIds);
        }

        private void BindRelatedInfo(string relatedInfos)
        {
            List<string> relatedIds = new List<string>();

            string[] ids = relatedInfos.Split(new char[] { ';' });

            foreach (string s in ids)
            {
                if (string.IsNullOrEmpty(s))
                    continue;

                relatedIds.Add(s);
            }

            BindRelated(relatedIds);
        }

        private void BindRelated(List<string> relatedIds)
        {
            tblRelated.Rows.Clear();
            tblRelatedGlobal.Rows.Clear();

            DataSet dataSet = RelatedInformationBLL.GetAllByGolbal();
            if (dataSet.Tables.Count == 0) return;
            DataTable table = dataSet.Tables[0];
            int count = table.Rows.Count;

            TableRow row = new TableRow();
            TableCell cell;

            string globalResult = string.Empty;
            string result = string.Empty;
            string defaultResultIds = string.Empty;

            for (int i = 0; i < count; i++)
            {
                if (table.Rows[i]["IsGlobal"].ToString().Equals("1"))
                {
                    string titleGlobal = table.Rows[i]["Title"].ToString() + " （全局）";
                    string urlGlobal = table.Rows[i]["Url"].ToString();

                    ItemShowing relatedGlobal = new ItemShowing(true, false, titleGlobal, urlGlobal);
                    relatedGlobal.Id = table.Rows[i]["Id"].ToString();
                    relatedGlobal.CssClass = "RelGlobalCss";

                    cell = new TableCell();

                    cell.Controls.Add(relatedGlobal);
                    cell.Style.Add("width", "400px");
                    cell.Style.Add("padding", "5px");
                    row.Cells.Add(cell);

                    tblRelatedGlobal.Rows.Add(row);
                    row = new TableRow();

                    globalResult += titleGlobal + ",";
                    continue;
                }

                bool isCheck = false;
                if (relatedIds.Contains(table.Rows[i]["Id"].ToString()))
                {
                    isCheck = true;
                    result += table.Rows[i]["Title"].ToString() + ",";
                    defaultResultIds += table.Rows[i]["Id"].ToString() + ";";
                }

                string title = table.Rows[i]["Title"].ToString();
                string url = table.Rows[i]["Url"].ToString();

                ItemShowing related = new ItemShowing(isCheck, true, title, url);
                related.Id = table.Rows[i]["Id"].ToString();
                related.CssClass = "RelCss";

                cell = new TableCell();

                cell.Controls.Add(related);
                cell.Style.Add("width", "400px");
                cell.Style.Add("padding", "5px");
                row.Cells.Add(cell);

                tblRelated.Rows.Add(row);
                row = new TableRow();

                continue;

            }

            globalRelated.Value = globalResult;
            defaultRelated.Value = result;
            hiddenRelChosen.Value = defaultResultIds;
        }

        private void BindTechnologyInfo(bool isNew)
        {
            List<string> technologyIds = new List<string>();

            if (!isNew)
            {
                CaseStudyInfo caseStudyInfo = CaseStudyBLL.GetInfo(id);
                string tIds = caseStudyInfo.Technology;
                string[] ids = tIds.Split(new char[] { ';' });

                foreach (string s in ids)
                {
                    if (string.IsNullOrEmpty(s))
                        continue;

                    technologyIds.Add(s);
                }
            }

            BindTechnology(technologyIds);
        }

        private void BindTechnologyInfo(string technologys)
        {
            List<string> technologyIds = new List<string>();

            string tIds = technologys;
            string[] ids = tIds.Split(new char[] { ';' });

            foreach (string s in ids)
            {
                if (string.IsNullOrEmpty(s))
                    continue;

                technologyIds.Add(s);
            }

            BindTechnology(technologyIds);
        }

        private void BindTechnology(List<string> technologyIds)
        {
            tblTechnology.Rows.Clear();

            DataSet dataSet = TechnologyBLL.GetAll();
            if (dataSet.Tables.Count == 0) return;
            DataTable table = dataSet.Tables[0];
            int count = table.Rows.Count;

            TableRow row = new TableRow();
            TableCell cell;

            string result = string.Empty;
            string defaultResultIds = string.Empty;

            for (int i = 0; i < count; i++)
            {
                bool isCheck = false;
                if (technologyIds.Contains(table.Rows[i]["Id"].ToString()))
                {
                    isCheck = true;
                    result += table.Rows[i]["Value"].ToString() + ",";
                    defaultResultIds += table.Rows[i]["Id"].ToString() + ";";
                }

                string title = table.Rows[i]["Value"].ToString();

                ItemShowing technolgy = new ItemShowing(isCheck, true, title, string.Empty);
                technolgy.Id = table.Rows[i]["Id"].ToString();
                technolgy.CssClass = "TechCss";

                cell = new TableCell();

                cell.Controls.Add(technolgy);
                cell.CssClass = "PopCell";
                row.Cells.Add(cell);

                if (row.Cells.Count == 3)
                {
                    tblTechnology.Rows.Add(row);
                    row = new TableRow();
                    continue;
                }

                if ((count - i) == 1)
                {
                    tblTechnology.Rows.Add(row);
                }
            }

            defaultTechnology.Value = result;
            hiddenTechChosen.Value = defaultResultIds;
        }

        private void SaveImage()
        {
            if (!loadImage.HasFile) return;

            string fileName = loadImage.FileName;
            int allowSize = -1;
            int.TryParse(size, out allowSize);
            allowSize = allowSize * 1048576;

            if ((allowSize > 0) && (loadImage.PostedFile.ContentLength >= allowSize))
            {
                divReminding.InnerHtml = "图片太大了！";
                divReminding.Visible = true;
                return;
            }

            string adminPath = Server.MapPath("~");
            loadImage.PostedFile.SaveAs(adminPath + "\\images\\" + fileName);
            loadImage.PostedFile.SaveAs(imagePath + "\\" + fileName);
        }

        private bool ValidateDates()
        {
            if (string.IsNullOrEmpty(txtTitle.Text))
            {
                divReminding.InnerHtml = "标题不能为空！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false ;
            }

            if (HttpUtility.HtmlEncode(txtTitle.Text).Length > 199)
            {
                divReminding.InnerHtml = "标题太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtDescription.Text).Length > 499)
            {
                divReminding.InnerHtml = "描述太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtFileName.Text).Length > 49)
            {
                divReminding.InnerHtml = "文件名太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }
            else if (!string.IsNullOrEmpty(txtFileName.Text) && 
                !txtFileName.Text.ToLower().EndsWith(".htm") &&
                !txtFileName.Text.ToLower().EndsWith(".html"))
            {
                divReminding.InnerHtml = "请输入HTML类型的文件名称！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (loadImage.HasFile)
            {
                string fileName = loadImage.FileName;
                string fileType = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
                if (!fileType.ToLower().Equals(".jpg") &&
                    !fileType.ToLower().Equals(".jpeg") &&
                    !fileType.ToLower().Equals(".gif") &&
                    !fileType.ToLower().Equals(".png"))
                {
                    divReminding.InnerHtml = "请选择图片格式的文件上传！";
                    divReminding.Visible = true;
                    return false;
                }
            }

            if (hiddenIndustry.Value.Equals("1") && 
                HttpUtility.HtmlEncode(txtIndustry.Text).Length > 49)
            {
                divReminding.InnerHtml = "新建行业名称太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (hiddenClient.Value.Equals("1") && 
                HttpUtility.HtmlEncode(txtClient.Text).Length > 49)
            {
                divReminding.InnerHtml = "新建客户名称太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (hiddenService.Value.Equals("1") && 
                HttpUtility.HtmlEncode(txtService.Text).Length > 49)
            {
                divReminding.InnerHtml = "新建服务类型名称太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtCapability.Text).Length > 49)
            {
                divReminding.InnerHtml = "性能属性说明太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtQuote.Text).Length > 49)
            {
                divReminding.InnerHtml = "引述太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtLocation.Text).Length > 49)
            {
                divReminding.InnerHtml = "位置说明太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (string.IsNullOrEmpty(txtOrganizationSize.Text))
            {
                txtOrganizationSize.Text = "0";
            }
            int organizationSize = -1;
            int.TryParse(txtOrganizationSize.Text, out organizationSize);
            if ((organizationSize < 0) || (!txtOrganizationSize.Text.Equals("0") && organizationSize == 0))
            {
                divReminding.InnerHtml = "组织规模处请填写数字！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtOrganizationProfile.Text).Length > 499)
            {
                divReminding.InnerHtml = "组织说明太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }


            if (HttpUtility.HtmlEncode(txtCountry.Text).Length > 49)
            {
                divReminding.InnerHtml = "国家和地区太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            return true;
        }
    }
}
